/*
 * EventLoopThread.cc
 *
 *  Created on: 2021年4月6日
 *      Author: san
 */

#include "EventLoopThread.h"

namespace san {

EventLoopThread::EventLoopThread()
	: loop_(NULL),
	  exiting_(false),
	  thread_(std::bind(&EventLoopThread::threadFunc, this), "EventLoopThread"),
	  mutex_(),
	  cond_(mutex_)
{
}

EventLoopThread::~EventLoopThread()
{
	exiting_ = true;
	if (loop_ != NULL)
	{
		loop_->quit();

		// join()
		thread_.join();
	}
}


EventLoop *EventLoopThread::startLoop()
{
	assert(!thread_.started());
	thread_.start();
	{
		MutexLockGuard lock(mutex_);
		// 一直等到 threadFunc 在 Thread 里真正跑起来
		while (loop_ == NULL) cond_.wait();
	}
	return loop_;
}

void EventLoopThread::threadFunc()
{
	EventLoop loop;
	{
		MutexLockGuard lock(mutex_);
		loop_ = &loop;
		cond_.notify();
	}

	loop.loop();
	// assert(exiting_);
	loop_ = NULL;
}


} /* namespace san */
